package xcmg.device.service.task;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.service.vo.company.CompanyInfoVO;
import xcmg.syn.feign.SynClient;
import xcmg.syn.service.vo.mmpart.MmPartSupplierVO;
import yb.ecp.fast.infra.infra.ActionResult;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@RefreshScope
public class SyncMmPartSupplierTaskService {

    private static final Integer BATCH_SIZE = 5000;

    @Autowired
    private SynClient synClient;
    //    @Autowired
//    private CommonGenService commonGenService;
    @Autowired
    private PriMaterialsMapper priMaterialsMapper;
    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    public void syncGpsPartSupplier(Date t, String querySupplierNo, String queryArrFactory) {
        log.info("syncGpsPartSupplier 同步执行--开始，t：{} querySupplierNo:{}", t, querySupplierNo);

        CompanyInfoDO g1CompanyInfo = companyInfoMapper.itemByOrgCode("GAC");
//        CompanyInfoDO g2CompanyInfo = companyInfoMapper.itemByOrgCode("G2");
        if (g1CompanyInfo == null) {
            log.error("没有找到G1和G2的核心企业");
            return;
        }
        List<String> fOrgIds = Lists.newArrayList(g1CompanyInfo.getOrgId());
        //相关公司的缓存，只查询一次
        Map<String, CompanyInfoDO> companyCache = new HashMap<>();
        MmPartSupplierVO gpsPartVO = new MmPartSupplierVO();
        String maxPartNo = null;
        while (true) {
            //如果有时间，根据时间增量同步
            gpsPartVO.setLastModifiedTimeStart(t);
            gpsPartVO.setLimitNum(BATCH_SIZE);
            //如果有传参，则只同步传参的供应商
            gpsPartVO.setSupplierNo(querySupplierNo);
            //如果有传参，则只同步传参的工厂
            gpsPartVO.setArrFactory(queryArrFactory);
            gpsPartVO.setMinPartNo(maxPartNo);
            ActionResult<List<MmPartSupplierVO>> listActionResult = synClient.listPartSupplier(gpsPartVO);
            if (listActionResult.getCode() != 0) {
                log.error("同步GPS数据失败,gpsPartVO：{}", gpsPartVO);
                break;
            }
            List<MmPartSupplierVO> partSupplierVOList = listActionResult.getValue();
            if (CollectionUtils.isEmpty(partSupplierVOList)) {
                log.info("没有需要同步的GPS数据");
                break;
            }
            boolean fullPage = (partSupplierVOList.size() == BATCH_SIZE);
            maxPartNo = partSupplierVOList.get(partSupplierVOList.size() - 1).getPartNo();
            //查询零件在核心企业的零件信息，key:零件号+工厂ID
            Map<String, PriMaterialsDO> priMaterialsDOMap = queryAllPriMaterials(partSupplierVOList, fOrgIds);
            List<PriMaterialsDO> updateList = new ArrayList<>();
            for (MmPartSupplierVO partSupplierVO : partSupplierVOList) {
                String partNo = partSupplierVO.getPartNo();
                String factoryId = "GAC";//partSupplierVO.getArrFactory();
                String supplierNo = partSupplierVO.getSupplierNo();
                if (partNo == null || null == supplierNo) {//|| factoryId == null
                    continue;
                }
                CompanyInfoDO companyInfoDO = queryCommpanyInfo(supplierNo, companyCache, querySupplierNo, queryArrFactory);
                if (null == companyInfoDO) {
                    log.error("没有找到对应的供应商,supplierNo：{},factoryId:{}", supplierNo, factoryId);
                    continue;
                }
                //核心企业下面的零件
                PriMaterialsDO mainPrieMaterialsDO = priMaterialsDOMap.get(partNo);
                String orgId = companyInfoDO.getOrgId();
                PriMaterialsDO priMaterialsDO = new PriMaterialsDO();
                priMaterialsDO.setMaterialsNo(partNo);
                priMaterialsDO.setOrgId(orgId);
                priMaterialsDO.setArrFactory(factoryId);
                priMaterialsDO.setCreateDate(partSupplierVO.getCreationTime());
                priMaterialsDO.setUpdateDate(partSupplierVO.getLastModifiedTime());
                //额外的字段
                priMaterialsDO.setPackStandard(partSupplierVO.getPackStandard());
                priMaterialsDO.setPackQuantity(partSupplierVO.getPackQuantity());
                priMaterialsDO.setMinnum(partSupplierVO.getMinnum());
                priMaterialsDO.setPrio(partSupplierVO.getPrio());
                priMaterialsDO.setEffStart(partSupplierVO.getEffStart());
                priMaterialsDO.setFactoryId(partSupplierVO.getFactoryId());
                if (null != mainPrieMaterialsDO) {
                    priMaterialsDO.setMaterialsDes(mainPrieMaterialsDO.getMaterialsDes());
                    priMaterialsDO.setMaterialsDesEn(mainPrieMaterialsDO.getMaterialsDesEn());
                    priMaterialsDO.setMaterialsShortNo(mainPrieMaterialsDO.getMaterialsShortNo());
                    priMaterialsDO.setUnit(mainPrieMaterialsDO.getUnit());
                    priMaterialsDO.setModelCode(mainPrieMaterialsDO.getModelCode());
                    priMaterialsDO.setPurchaseType(mainPrieMaterialsDO.getPurchaseType());
                }
                updateList.add(priMaterialsDO);
            }
            if (CollectionUtils.isNotEmpty(updateList)) {
//                updateList.forEach(priMaterialsDO -> priMaterialsMapper.addOrUpdateGps(priMaterialsDO));
                Lists.partition(updateList, 50).forEach(priMaterialsDOList -> {
                    priMaterialsMapper.batchSaveGps(priMaterialsDOList);
                });
            }
            if (!fullPage) {
                log.info("当前查询不满页,同步GPS数据完成,size:{},maxPartNo:{}", partSupplierVOList.size(), maxPartNo);
                break;
            } else {
                log.info("当前查询满页,maxPartNo:{}", maxPartNo);
            }
        }
    }

    private CompanyInfoDO queryCommpanyInfo(String key, Map<String, CompanyInfoDO> comMap, String querySupplierNo, String queryArrFactory) {
        if (comMap.isEmpty()) {
            CompanyInfoVO cp = new CompanyInfoVO();
            cp.setDel(false);
            cp.setSupplierNo(querySupplierNo);
            //如果有传参，则只同步传参的工厂
            cp.setFactoryId(queryArrFactory);
            List<CompanyInfoDO> comList = companyInfoMapper.list(cp);
            if (CollectionUtils.isEmpty(comList)) {
                log.error("没有找到供应商");
                comMap.put("", null);
                return null;
            }
            comMap.putAll(comList.stream().collect(java.util.stream.Collectors.toMap(x -> x.getSupplierNo(), v -> v, (x, y) -> x)));
        }
        return comMap.get(key);
    }

    private Map<String, PriMaterialsDO> queryAllPriMaterials(List<MmPartSupplierVO> partSupplierVOList, List<String> fOrgIds) {
        Map<String, PriMaterialsDO> r = new HashMap<>(partSupplierVOList.size());
        List<PriMaterialsDO> queryList = new ArrayList<>(partSupplierVOList.size());
        partSupplierVOList.forEach(item -> {
            String partNo = item.getPartNo();
//            String factoryId = item.getArrFactory();
            String factoryId = "GAC";
            PriMaterialsDO pm = new PriMaterialsDO();
            pm.setMaterialsNo(partNo);
            pm.setArrFactory(factoryId);
            queryList.add(pm);
        });
        Lists.partition(queryList, 1000).forEach(item -> {
            List<PriMaterialsDO> list = priMaterialsMapper.queryG1G2Materials(item, fOrgIds);
            list.forEach(priMaterialsDO -> {
                String mkey = priMaterialsDO.getMaterialsNo();//+ priMaterialsDO.getArrFactory();
                r.put(mkey, priMaterialsDO);
            });
        });
        return r;
    }
}
